import json

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse
from django.shortcuts import render

from Spider import song_spider
from .models import SongList


# Create your views here.

def index(request):
    return render(request, 'index.html')


def song_list(request):
    return render(request, 'song_list.html')


def get_song_list(request):
    song_list = song_spider.get_song_list_by_cat('全部', 10)
    if song_list:
        for song in song_list:
            _song = SongList()
            _song.name = song['name']
            _song.creator = song['creator']
            _song.url = song['url']
            _song.view_counts = song['view_counts']
            _song.save()
            print(_song)
    return render(request, 'index.html', {'success': '成功'})


def show_song_list(request):
    if request.method == 'GET':
        page = request.GET.get('page', 1)
        limit = request.GET.get('limit', 10)
        song_list = SongList.objects.all()
        paginator = Paginator(song_list, limit)
        try:
            customer = paginator.page(page)
        except PageNotAnInteger:
            customer = paginator.page(1)
        except EmptyPage:
            customer = paginator.page(paginator.num_pages)
        song_list_dto = []
        for song in customer.object_list:
            song_list_dto.append(
                {'id': song.id, 'name': song.name, 'creator': song.creator, 'url': song.url,
                 'view_counts': song.view_counts})
        res = json.dumps({'code': 0, 'msg': '', 'count': len(song_list), 'data': song_list_dto})
    return HttpResponse(res, content_type='application/json')
